<template>
  <view class="fix-page">
    <!-- 问题说明 -->
    <view class="problem-card">
      <view class="problem-header">
        <text class="problem-icon">🚨</text>
        <text class="problem-title">412错误解决方案</text>
      </view>
      
      <view class="problem-desc">
        <text class="desc-text">
          根据后端日志分析，您遇到的是典型的"用户未订阅模板消息"问题。
          请按照以下步骤解决：
        </text>
      </view>
    </view>

    <!-- 解决步骤 -->
    <view class="solution-steps">
      <!-- 步骤1: 检查当前状态 -->
      <view class="step-card" :class="{ 'completed': step1Done }">
        <view class="step-header">
          <view class="step-number">1</view>
          <text class="step-title">检查当前配置</text>
          <text class="step-status" v-if="step1Done">✅</text>
        </view>
        
        <view class="step-content">
          <view class="config-display" v-if="configInfo">
            <view class="config-row">
              <text class="config-label">小程序AppID:</text>
              <text class="config-value">{{ configInfo.currentAppId }}</text>
            </view>
            <view class="config-row">
              <text class="config-label">后端AppID:</text>
              <text class="config-value">{{ configInfo.backendAppId }}</text>
            </view>
            <view class="config-row">
              <text class="config-label">匹配状态:</text>
              <text class="config-value" :class="configInfo.match ? 'success' : 'error'">
                {{ configInfo.match ? '✅ 匹配' : '❌ 不匹配' }}
              </text>
            </view>
          </view>
          
          <button class="step-btn" @click="checkConfig" :loading="checking">
            {{ checking ? '检查中...' : '检查配置' }}
          </button>
        </view>
      </view>

      <!-- 步骤2: 订阅消息 -->
      <view class="step-card" :class="{ 'completed': step2Done, 'disabled': !step1Done }">
        <view class="step-header">
          <view class="step-number">2</view>
          <text class="step-title">订阅消息模板</text>
          <text class="step-status" v-if="step2Done">✅</text>
        </view>
        
        <view class="step-content">
          <view class="subscribe-info">
            <text class="info-text">
              🎯 这是解决412错误的关键步骤！
              点击下方按钮，在弹出的授权框中选择"允许"
            </text>
          </view>
          
          <button 
            class="step-btn primary" 
            @click="subscribeMessage" 
            :loading="subscribing"
            :disabled="!step1Done"
          >
            {{ subscribing ? '订阅中...' : '🔔 订阅消息模板' }}
          </button>
          
          <view class="subscribe-result" v-if="subscribeResult">
            <text class="result-text" :class="subscribeResult.success ? 'success' : 'error'">
              {{ subscribeResult.message }}
            </text>
          </view>
        </view>
      </view>

      <!-- 步骤3: 立即测试 -->
      <view class="step-card" :class="{ 'completed': step3Done, 'disabled': !step2Done }">
        <view class="step-header">
          <view class="step-number">3</view>
          <text class="step-title">立即发送测试</text>
          <text class="step-status" v-if="step3Done">✅</text>
        </view>
        
        <view class="step-content">
          <view class="test-info">
            <text class="info-text">
              ⚡ 订阅成功后必须立即测试！
              微信订阅消息有时效性，不要等待。
            </text>
          </view>
          
          <view class="test-buttons">
            <button 
              class="step-btn success" 
              @click="testSendMessage" 
              :loading="testing"
              :disabled="!step2Done"
            >
              {{ testing ? '发送中...' : '🚀 立即测试发送' }}
            </button>
            
            <button 
              class="step-btn default" 
              @click="testMinimalMessage" 
              :loading="testingMinimal"
              :disabled="!step2Done"
            >
              {{ testingMinimal ? '发送中...' : '📝 最简测试' }}
            </button>
          </view>
          
          <view class="test-result" v-if="testResult">
            <text class="result-text" :class="testResult.success ? 'success' : 'error'">
              {{ testResult.message }}
            </text>
            <view class="result-details" v-if="testResult.details">
              <text class="details-text">{{ testResult.details }}</text>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 重要提示 -->
    <view class="tips-card">
      <view class="tips-header">
        <text class="tips-icon">💡</text>
        <text class="tips-title">重要提示</text>
      </view>
      
      <view class="tips-content">
        <view class="tip-item">
          <text class="tip-text">🔄 每次订阅只能发送一次消息</text>
        </view>
        <view class="tip-item">
          <text class="tip-text">⏰ 订阅24小时后自动过期</text>
        </view>
        <view class="tip-item">
          <text class="tip-text">🎯 必须在订阅成功后立即测试</text>
        </view>
        <view class="tip-item">
          <text class="tip-text">📱 确保在正确的小程序中测试</text>
        </view>
      </view>
    </view>

    <!-- 快速操作 -->
    <view class="quick-actions">
      <button class="action-btn diagnose" @click="getDiagnosis">
        🔍 获取详细诊断
      </button>
      <button class="action-btn reset" @click="resetSteps">
        🔄 重新开始
      </button>
    </view>

    <!-- 诊断结果弹窗 -->
    <uni-popup ref="diagnosisPopup" type="center">
      <view class="diagnosis-popup">
        <view class="popup-header">
          <text class="popup-title">诊断结果</text>
          <text class="popup-close" @click="closeDiagnosis">✕</text>
        </view>
        
        <scroll-view scroll-y class="popup-content">
          <view class="diagnosis-section" v-for="(section, key) in diagnosisData" :key="key">
            <text class="section-title">{{ getSectionTitle(key) }}</text>
            <view class="section-content">
              <text 
                class="section-item" 
                v-for="(item, index) in section" 
                :key="index"
              >
                {{ item }}
              </text>
            </view>
          </view>
        </scroll-view>
      </view>
    </uni-popup>
  </view>
</template>

<script>
export default {
  data() {
    return {
      // 步骤状态
      step1Done: false,
      step2Done: false,
      step3Done: false,
      
      // 加载状态
      checking: false,
      subscribing: false,
      testing: false,
      testingMinimal: false,
      
      // 配置信息
      configInfo: null,
      
      // 结果信息
      subscribeResult: null,
      testResult: null,
      
      // 诊断数据
      diagnosisData: null,
      
      // 配置常量
      templateId: 'zvaRsziQ2U139jQdNUSSX8cCgyqHe_r5xIsuGo36wR8',
      backendAppId: 'wxfb22784840ae6d0c'
    }
  },
  
  onLoad() {
    this.showWelcomeMessage()
  },
  
  methods: {
    // 显示欢迎信息
    showWelcomeMessage() {
      uni.showModal({
        title: '412错误解决向导',
        content: '这个页面将帮助您解决微信订阅消息的412错误。请按照步骤操作，确保每一步都成功完成。',
        showCancel: false,
        confirmText: '开始解决'
      })
    },
    
    // 步骤1: 检查配置
    async checkConfig() {
      this.checking = true
      
      try {
        // #ifdef MP-WEIXIN
        const accountInfo = wx.getAccountInfoSync()
        const currentAppId = accountInfo.miniProgram.appId
        
        this.configInfo = {
          currentAppId: currentAppId,
          backendAppId: this.backendAppId,
          match: currentAppId === this.backendAppId
        }
        
        if (this.configInfo.match) {
          this.step1Done = true
          uni.showToast({
            title: '配置检查通过',
            icon: 'success'
          })
        } else {
          uni.showModal({
            title: '配置不匹配',
            content: `小程序AppID与后端配置不一致，这会导致订阅消息失败。\n\n当前: ${currentAppId}\n后端: ${this.backendAppId}`,
            showCancel: false
          })
        }
        // #endif
        
        // #ifndef MP-WEIXIN
        uni.showToast({
          title: '非微信小程序环境',
          icon: 'none'
        })
        // #endif
        
      } catch (error) {
        console.error('检查配置失败:', error)
        uni.showToast({
          title: '检查失败',
          icon: 'none'
        })
      } finally {
        this.checking = false
      }
    },
    
    // 步骤2: 订阅消息
    async subscribeMessage() {
      this.subscribing = true
      this.subscribeResult = null
      
      try {
        // #ifdef MP-WEIXIN
        console.log('开始订阅消息，模板ID:', this.templateId)
        
        const result = await uni.requestSubscribeMessage({
          tmplIds: [this.templateId]
        })
        
        console.log('订阅结果:', result)
        
        const subscribeStatus = result[this.templateId]
        
        if (subscribeStatus === 'accept') {
          this.step2Done = true
          this.subscribeResult = {
            success: true,
            message: '✅ 订阅成功！用户已同意接收消息通知'
          }
          
          uni.showToast({
            title: '订阅成功',
            icon: 'success'
          })
          
          // 订阅成功后提示立即测试
          setTimeout(() => {
            uni.showModal({
              title: '订阅成功',
              content: '订阅成功！请立即点击"立即测试发送"按钮，不要等待。微信订阅消息有时效性。',
              showCancel: false,
              confirmText: '立即测试',
              success: (res) => {
                if (res.confirm) {
                  this.testSendMessage()
                }
              }
            })
          }, 1000)
          
        } else if (subscribeStatus === 'reject') {
          this.subscribeResult = {
            success: false,
            message: '❌ 用户拒绝了订阅请求，请重新尝试并选择"允许"'
          }
          
        } else {
          this.subscribeResult = {
            success: false,
            message: `⚠️ 订阅状态未知: ${subscribeStatus}`
          }
        }
        // #endif
        
        // #ifndef MP-WEIXIN
        this.subscribeResult = {
          success: false,
          message: '⚠️ 非微信小程序环境，无法测试订阅功能'
        }
        // #endif
        
      } catch (error) {
        console.error('订阅失败:', error)
        this.subscribeResult = {
          success: false,
          message: `❌ 订阅异常: ${error.message}`
        }
      } finally {
        this.subscribing = false
      }
    },
    
    // 步骤3: 测试发送消息
    async testSendMessage() {
      this.testing = true
      this.testResult = null
      
      try {
        const response = await this.callAPI('/wechat/sendConfirmed')
        
        if (response.success) {
          this.step3Done = true
          this.testResult = {
            success: true,
            message: '🎉 发送成功！请查看微信通知',
            details: response.message
          }
          
          uni.showToast({
            title: '发送成功',
            icon: 'success'
          })
          
          // 成功后显示完成信息
          setTimeout(() => {
            uni.showModal({
              title: '测试完成',
              content: '恭喜！412错误已解决。订阅消息发送成功，请查看微信通知。',
              showCancel: false
            })
          }, 1500)
          
        } else {
          this.testResult = {
            success: false,
            message: '❌ 发送失败',
            details: response.message
          }
          
          // 如果还是412错误，说明订阅可能有问题
          if (response.message && response.message.includes('412')) {
            setTimeout(() => {
              uni.showModal({
                title: '仍然是412错误',
                content: '可能的原因：\n1. 订阅权限未生效，请重新订阅\n2. 时间间隔太长，请立即重试\n3. 模板配置问题',
                showCancel: false
              })
            }, 1000)
          }
        }
        
      } catch (error) {
        console.error('测试发送失败:', error)
        this.testResult = {
          success: false,
          message: '❌ 网络错误',
          details: error.message
        }
      } finally {
        this.testing = false
      }
    },
    
    // 测试最简消息
    async testMinimalMessage() {
      this.testingMinimal = true
      
      try {
        const response = await this.callAPI('/wechat/sendMinimal')
        
        if (response.success) {
          this.testResult = {
            success: true,
            message: '🎉 最简消息发送成功！',
            details: response.message
          }
        } else {
          this.testResult = {
            success: false,
            message: '❌ 最简消息发送失败',
            details: response.message
          }
        }
        
      } catch (error) {
        console.error('最简消息发送失败:', error)
        this.testResult = {
          success: false,
          message: '❌ 网络错误',
          details: error.message
        }
      } finally {
        this.testingMinimal = false
      }
    },
    
    // 获取诊断信息
    async getDiagnosis() {
      try {
        uni.showLoading({ title: '获取诊断中...' })
        
        const response = await this.callAPI('/wechat/diagnoseCurrent')
        
        if (response.success) {
          this.diagnosisData = response.data
          this.$refs.diagnosisPopup.open()
        } else {
          uni.showToast({
            title: '获取诊断失败',
            icon: 'none'
          })
        }
        
      } catch (error) {
        console.error('获取诊断失败:', error)
        uni.showToast({
          title: '网络错误',
          icon: 'none'
        })
      } finally {
        uni.hideLoading()
      }
    },
    
    // 重置步骤
    resetSteps() {
      uni.showModal({
        title: '重新开始',
        content: '确定要重新开始吗？这将清除所有进度。',
        success: (res) => {
          if (res.confirm) {
            this.step1Done = false
            this.step2Done = false
            this.step3Done = false
            this.configInfo = null
            this.subscribeResult = null
            this.testResult = null
            
            uni.showToast({
              title: '已重置',
              icon: 'success'
            })
          }
        }
      })
    },
    
    // 关闭诊断弹窗
    closeDiagnosis() {
      this.$refs.diagnosisPopup.close()
    },
    
    // 获取诊断区域标题
    getSectionTitle(key) {
      const titles = {
        logAnalysis: '📊 日志分析',
        confirmedIssues: '🎯 问题确诊',
        immediateSolution: '🚀 解决方案'
      }
      return titles[key] || key
    },
    
    // 调用后端API
    callAPI(endpoint) {
      return new Promise((resolve) => {
        uni.request({
          url: `http://localhost:9090${endpoint}`,
          method: 'GET',
          success: (res) => {
            console.log(`API ${endpoint} 响应:`, res)
            
            if (res.statusCode === 200) {
              resolve({
                success: res.data.code === '200',
                data: res.data.data,
                message: res.data.message
              })
            } else {
              resolve({
                success: false,
                message: `HTTP ${res.statusCode}: ${res.data.message || '请求失败'}`
              })
            }
          },
          fail: (error) => {
            console.error(`API ${endpoint} 失败:`, error)
            resolve({
              success: false,
              message: `网络错误: ${error.errMsg || '请求失败'}`
            })
          }
        })
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.fix-page {
  min-height: 100vh;
  background: linear-gradient(135deg, #ff9a9e 0%, #fecfef 100%);
  padding: 20rpx;
}

.problem-card, .tips-card {
  background: #fff;
  border-radius: 16rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 8rpx 32rpx rgba(0, 0, 0, 0.1);
}

.problem-header, .tips-header {
  display: flex;
  align-items: center;
  margin-bottom: 20rpx;
  
  .problem-icon, .tips-icon {
    font-size: 32rpx;
    margin-right: 12rpx;
  }
  
  .problem-title, .tips-title {
    font-size: 32rpx;
    font-weight: bold;
    color: #333;
  }
}

.problem-desc {
  .desc-text {
    font-size: 28rpx;
    color: #666;
    line-height: 1.6;
  }
}

.solution-steps {
  .step-card {
    background: #fff;
    border-radius: 16rpx;
    padding: 30rpx;
    margin-bottom: 20rpx;
    box-shadow: 0 8rpx 32rpx rgba(0, 0, 0, 0.1);
    transition: all 0.3s ease;
    
    &.completed {
      border-left: 6rpx solid #43e97b;
    }
    
    &.disabled {
      opacity: 0.6;
      pointer-events: none;
    }
    
    .step-header {
      display: flex;
      align-items: center;
      margin-bottom: 20rpx;
      
      .step-number {
        width: 60rpx;
        height: 60rpx;
        border-radius: 50%;
        background: linear-gradient(135deg, #ff9a9e 0%, #fecfef 100%);
        color: #fff;
        font-size: 28rpx;
        font-weight: bold;
        display: flex;
        align-items: center;
        justify-content: center;
        margin-right: 20rpx;
      }
      
      .step-title {
        flex: 1;
        font-size: 30rpx;
        font-weight: bold;
        color: #333;
      }
      
      .step-status {
        font-size: 32rpx;
      }
    }
    
    .step-content {
      padding-left: 80rpx;
    }
  }
}

.config-display {
  background: #f8f9fa;
  border-radius: 12rpx;
  padding: 20rpx;
  margin-bottom: 20rpx;
  
  .config-row {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 12rpx 0;
    border-bottom: 1px solid #eee;
    
    &:last-child {
      border-bottom: none;
    }
    
    .config-label {
      font-size: 26rpx;
      color: #666;
    }
    
    .config-value {
      font-size: 24rpx;
      font-family: monospace;
      
      &.success {
        color: #43e97b;
      }
      
      &.error {
        color: #ff4757;
      }
    }
  }
}

.subscribe-info, .test-info {
  background: rgba(255, 154, 158, 0.1);
  border-radius: 12rpx;
  padding: 20rpx;
  margin-bottom: 20rpx;
  
  .info-text {
    font-size: 26rpx;
    color: #666;
    line-height: 1.5;
  }
}

.step-btn {
  padding: 16rpx 32rpx;
  border-radius: 8rpx;
  font-size: 28rpx;
  border: none;
  
  &::after {
    border: none;
  }
  
  &.primary {
    background: linear-gradient(135deg, #ff9a9e 0%, #fecfef 100%);
    color: #fff;
  }
  
  &.success {
    background: linear-gradient(135deg, #43e97b 0%, #38d9a9 100%);
    color: #fff;
  }
  
  &.default {
    background: #f5f5f5;
    color: #666;
    margin-left: 20rpx;
  }
  
  &[disabled] {
    opacity: 0.5;
  }
}

.test-buttons {
  display: flex;
  gap: 20rpx;
  flex-wrap: wrap;
}

.subscribe-result, .test-result {
  margin-top: 20rpx;
  padding: 16rpx 20rpx;
  border-radius: 8rpx;
  
  .result-text {
    font-size: 26rpx;
    line-height: 1.4;
    
    &.success {
      color: #43e97b;
    }
    
    &.error {
      color: #ff4757;
    }
  }
  
  .result-details {
    margin-top: 12rpx;
    
    .details-text {
      font-size: 22rpx;
      color: #999;
    }
  }
}

.tips-content {
  .tip-item {
    padding: 12rpx 0;
    border-bottom: 1px solid #f0f0f0;
    
    &:last-child {
      border-bottom: none;
    }
    
    .tip-text {
      font-size: 26rpx;
      color: #666;
      line-height: 1.4;
    }
  }
}

.quick-actions {
  display: flex;
  gap: 20rpx;
  margin-top: 20rpx;
  
  .action-btn {
    flex: 1;
    padding: 20rpx;
    border-radius: 12rpx;
    font-size: 28rpx;
    font-weight: bold;
    border: none;
    
    &::after {
      border: none;
    }
    
    &.diagnose {
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      color: #fff;
    }
    
    &.reset {
      background: linear-gradient(135deg, #ffeaa7 0%, #fab1a0 100%);
      color: #333;
    }
  }
}

.diagnosis-popup {
  width: 600rpx;
  max-height: 800rpx;
  background: #fff;
  border-radius: 16rpx;
  overflow: hidden;
  
  .popup-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 30rpx;
    background: linear-gradient(135deg, #ff9a9e 0%, #fecfef 100%);
    
    .popup-title {
      font-size: 32rpx;
      font-weight: bold;
      color: #fff;
    }
    
    .popup-close {
      font-size: 32rpx;
      color: #fff;
      padding: 8rpx;
    }
  }
  
  .popup-content {
    max-height: 600rpx;
    padding: 30rpx;
    
    .diagnosis-section {
      margin-bottom: 30rpx;
      
      .section-title {
        display: block;
        font-size: 28rpx;
        font-weight: bold;
        color: #333;
        margin-bottom: 16rpx;
      }
      
      .section-content {
        .section-item {
          display: block;
          font-size: 24rpx;
          color: #666;
          line-height: 1.5;
          margin-bottom: 8rpx;
          padding-left: 20rpx;
        }
      }
    }
  }
}
</style>
